package com.huayal.mall.ware.service.impl;

import com.huayal.common.constant.WareConstant;
import com.huayal.mall.ware.entity.PurchaseDetailEntity;
import com.huayal.mall.ware.service.PurchaseDetailService;
import com.huayal.mall.ware.service.WareSkuService;
import com.huayal.mall.ware.vo.MergeVo;
import com.huayal.mall.ware.vo.PurchaseDoneVo;
import com.huayal.mall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huayal.common.utils.PageUtils;
import com.huayal.common.utils.Query;

import com.huayal.mall.ware.dao.PurchaseDao;
import com.huayal.mall.ware.entity.PurchaseEntity;
import com.huayal.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceiveListPage(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public int merge(MergeVo mergeVo) {

        //先过滤数据
        List<Long> items = mergeVo.getItems().stream().filter(id -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(id);
            if (purchaseDetailEntity.getStatus() >= WareConstant.PurchaseItemStatusEnum.PURCHASING.getCode()) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        if (items.size()==0)return -1;

        Long purchaseId = mergeVo.getPurchaseId();
        //无采购单自动创建
        if (purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.NEWLY_BUILT.getCode());
            purchaseEntity.setCreateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }else {
            //过滤采购单：状态>=已领取
            PurchaseEntity purchaseEntity = this.getById(purchaseId);
            if (purchaseEntity.getStatus()>=WareConstant.PurchaseStatusEnum.RECEIVED.getCode()){
                return -1;
            }
        }
        final Long purchaseId1=purchaseId;

        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(e -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(e);
            purchaseDetailEntity.setPurchaseId(purchaseId1);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseItemStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId1);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        return 1;
    }

    @Transactional
    @Override
    public void receive(List<Long> ids) {

        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            return this.baseMapper.selectById(id);
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.NEWLY_BUILT.getCode()) {
                return true;
            }
            return false;
        }).map(item->{
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(item.getId());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());

        this.updateBatchById(purchaseEntities);

        for (PurchaseEntity purchaseEntity:purchaseEntities){
            List<PurchaseDetailEntity> purchaseDetails=purchaseDetailService.getBaseMapper()
                    .selectList(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id",purchaseEntity.getId()));
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetails.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseItemStatusEnum.PURCHASING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        }
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {

        //获取采购编号
        Long id = purchaseDoneVo.getId();
        //2，改变采购项的状态
        Boolean flag=true;//记录采购项的状态 默认完成
        //获取所有的采购项
        List<PurchaseDetailEntity> list = new ArrayList<>();
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        for (PurchaseItemDoneVo item:items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseItemStatusEnum.PURCHASE_FAILURE.getCode()) {
                //该采购项出现了问题
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseItemStatusEnum.PURCHASE_FAILURE.getCode());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseItemStatusEnum.COMOLETED.getCode());
                //3，将采购成功的采购项进行入库操作
                //根据采购项编号查询出对应的采购项详情
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            list.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(list);


        //1，改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.COMOLETED.getCode():WareConstant.PurchaseStatusEnum.ABNORMAL.getCode());
        this.updateById(purchaseEntity);

    }

}